package com.xiaozhichao.mybatis;

import com.xiaozhichao.mybatis.domain.Book;
import com.xiaozhichao.mybatis.mapper.BookMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@SuppressWarnings("all")
public class MybatisCacheTest {

    private static SqlSessionFactory factory = null;
    private static SqlSession sqlSession = null;

    @Before
    public void before(){
        // 加载配置文件 并构建SqlSessionFactory对象
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        factory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = factory.openSession();
    }

    @After
    public void after(){
        if(Objects.nonNull(sqlSession)){
            // 关闭SqlSession
            sqlSession.close();
        }
    }

    /**
     * 一级缓存测试
     */
    @Test
    public void testCashFirst(){
        // 创建一个book对象
        /*Book bookInsert = new Book();
        bookInsert.setName("testCashFirst");
        bookInsert.setNumber(110);*/

        BookMapper mapper = sqlSession.getMapper(BookMapper.class);
        Book book = mapper.selectByPrimaryKey(4);
        sqlSession.clearCache();
        System.out.println(book.getName());

        /*book.setName("testCashFirst");
        mapper.updateByPrimaryKey(book);*/

        Book book1 = mapper.selectByPrimaryKey(4);
        System.out.println(book.getName());

    }
}
